import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:riverpod_t/config/response_model.dart';
import 'package:riverpod_t/page/home/data/model/cartoon_model_entity.dart';
import 'package:riverpod_t/page/home/data/repository/home_repository.dart';
import 'package:riverpod_t/page/home/state/home_state.dart';
import 'package:riverpod_t/until/app_util.dart';
part 'home_list_river.g.dart';

/// 典型的列表 -> riverpod 案例
@riverpod
class HomeListRiver extends _$HomeListRiver {
  @override
  Future<HomeState> build() async {
    /// 监听操作river变化去刷新数据
    // ref.listen(homeListOpRiverProvider, _listenOpChange);

    /// 请求数据返回 state
    /// 1. build() 方法的特殊作用
    // 在 @riverpod 生成的异步 Notifier 中：
    // build() 的返回值会自动赋值给 state
    // 当你返回 HomeState 时，Riverpod 内部会将其包装为 AsyncValue.data(HomeState(...))，并更新 state。
    // 异步 build() 会自动处理 loading 状态
    // 由于 build() 是 async 函数，在 await _fetchAllList() 执行期间：
    // 框架会先设置 state = AsyncValue.loading()（自动处理）
    // 数据返回后，再设置 state = AsyncValue.data(result)
    ///

    return HomeState(list: await _fetchAllList(1));
  }

  /// 刷新方法
  void refresh({bool isRefresh = false}) async {
    try {
      int page = state.value?.page ?? 1;
      List<CartoonModelDataFeeds> list = state.value?.list ?? [];
      bool hasNext = true;
      if (isRefresh) {
        page = 1;
      } else {
        page++;
      }
      List<CartoonModelDataFeeds>? moreList = await _fetchAllList(page);
      if (AppUtil.isNotEmpty(moreList)) {
        if (isRefresh) {
          list.clear();
        }
        list.addAll(moreList);
        if (moreList.length >= 20) {
          hasNext = true;
        } else {
          hasNext = false;
        }
      } else {
        hasNext = false;
      }

      state = AsyncValue.data(HomeState(list: list, page: page, hasNext: hasNext));
    } catch (err, stack) {
      state = AsyncValue.error(err, stack);
    }
  }

  /// 点赞方法
  void giveLike(String itemId) {
    List<CartoonModelDataFeeds> list = state.value?.list ?? [];
    final index = list.indexWhere((element) => element.itemId == itemId);
    if (index > -1) {
      CartoonModelDataFeeds model = list[index];
      model.isLike = !model.isLike;
      state = AsyncValue.data(HomeState(list: list));
    }
  }

  Future<List<CartoonModelDataFeeds>> _fetchAllList(int page) async {
    ResponseModel model = await HomeRepository.getListData<CartoonModelData>(page);
    CartoonModelData carDataModel = model.data;
    return carDataModel.feeds ?? [];
  }
}
